<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
      class="form-search"
    >
      <SearchTool
        v-model:factory="queryParams.factory"
        :showWorkshop="false"
        :showLine="false"
        :showSection="false"
      ></SearchTool>
      <!-- <el-form-item label="物料分类" prop="typeName">
        <el-input
          v-model="queryParams.typeName"
          placeholder="请选择物料分类"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="物料编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入物料编号"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入物料名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料分类" prop="type">
        <el-tree-select
          v-model="queryParams.type"
          :data="matTypes"
          :check-on-click-node="true"
          node-key="typeCode"
          highlight-current
          filterable
          check-strictly
          :expand-on-click-node="false"
          :props="{ label: 'name', children: 'children' }"
          :render-after-expand="false"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['base:matMaterial:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:matMaterial:delete']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          :loading="syncLoading"
          type="warning"
          plain
          icon="Refresh"
          @click="handleSync"
          v-hasPermi="['base:material:sync']"
          >同步ERP数据</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="typeList"
      border
      :max-height='500'
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="物料编号"
        align="center"
        prop="code"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <el-link type="primary" @click="handleDetail(scope.row)">{{
            scope.row.code
          }}</el-link>
        </template>
      </el-table-column>

      <el-table-column
        label="物料名称"
        align="center"
        prop="name"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="物料分类"
        align="center"
        prop="typeName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="工厂"
        align="center"
        prop="factoryName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="规格"
        align="center"
        prop="packages"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="单位"
        align="center"
        prop="measureUnit"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="型号"
        align="center"
        prop="model"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="品牌"
        align="center"
        prop="brand"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="修改时间"
        align="center"
        prop="updateTime"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="来源"
        align="center"
        prop="source"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="操作"
        align="center"
        width="160"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            v-if="scope.row.source !== 'ERP'"
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['base:matMaterial:edit']"
            >编辑</el-button
          >
          <el-button
            v-if="scope.row.source !== 'ERP'"
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['base:matMaterial:delete']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      :close-on-click-modal="false"
      width="700px"
      append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="gutter">
          <el-col :span="span">
            <el-form-item label="物料编号" prop="code">
              <code-input
                v-if="!disabledForm"
                v-model="form.code"
                code="MAT_CODE"
                placeholder="请输入物料编号"
              />
              <div v-else>{{ form.code }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item label="物料名称" prop="name">
              <el-input
                v-if="!disabledForm"
                v-model="form.name"
                placeholder="请输入物料名称"
              />
              <div v-else>{{ form.name }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item label="物料分类" prop="type">
              <el-tree-select
                v-if="!disabledForm"
                v-model="form.type"
                :data="matTypes"
                :check-on-click-node="true"
                node-key="typeCode"
                highlight-current
                @node-click="addTreeClick"
                check-strictly
                :expand-on-click-node="false"
                :props="{ label: 'name', children: 'children' }"
                :render-after-expand="false"
              />
              <div v-else>{{ form.typeName }}</div>
            </el-form-item>
          </el-col>
          <SearchTool
            :layout="true"
            :span="span"
            v-if="!disabledForm"
            v-model:factory="form.factory"
            :showWorkshop="false"
            :showLine="false"
            :showSection="false"
          ></SearchTool>
          <el-col v-if="disabledForm" :span="span">
            <el-form-item label="工厂" prop="factory">
              <div>{{ form.factoryName }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item label="单位" prop="measureUnit">
              <el-input
                v-if="!disabledForm"
                v-model="form.measureUnit"
                placeholder="请输入单位"
              />
              <div v-else>{{ form.measureUnit }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item label="规格" prop="packages">
              <el-input
                v-if="!disabledForm"
                v-model="form.packages"
                placeholder="请输入包装规格"
              />
              <div v-else>{{ form.packages }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item label="型号" prop="model">
              <el-input
                v-if="!disabledForm"
                v-model="form.model"
                placeholder="请输入单位"
              />
              <div v-else>{{ form.model }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item label="品牌" prop="brand">
              <el-input
                v-if="!disabledForm"
                v-model="form.brand"
                placeholder="请输入包装规格"
              />
              <div v-else>{{ form.brand }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item label="单位体积" prop="volume">
              <el-input
                v-if="!disabledForm"
                v-model="form.volume"
                placeholder="请输入单位体积"
              />
              <div v-else>{{ form.volume }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item label="单位重量" prop="weight">
              <el-input
                v-if="!disabledForm"
                v-model="form.weight"
                placeholder="请输入单位重量"
              />
              <div v-else>{{ form.weight }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="span" v-if="disabledForm">
            <el-form-item label="创建时间" prop="weight">
              <div>{{ form.createTime }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="span" v-if="disabledForm">
            <el-form-item label="修改时间" prop="weight">
              <div>{{ form.updateTime }}</div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!disabledForm" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button v-if="!disabledForm" @click="cancel">取 消</el-button>
          <el-button v-if="disabledForm" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="bom">
import {
  listMat,
  getMat,
  delMat,
  addMat,
  updateMat,
  syncErpMaterial,
} from "@/api/base/material/MaterialApi";
import { queryMatTypeTree } from "@/api/base/material/MatTypeApi";
import { ref, reactive, toRefs,getCurrentInstance,computed } from "vue";
const { proxy } = getCurrentInstance();
// const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const typeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const matTypes = ref([]);
const syncLoading = ref(false);
const disabledForm = ref(false);
const selectData = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    equipNo: undefined,
    name: undefined,
    status: undefined,
  },
  rules: {
    code: [{ required: true, message: "请输入物料编号!", trigger: "blur" }],
    name: [{ required: true, message: "请输入物料名称!", trigger: "blur" }],
    type: [{ required: true, message: "请输入物料类别!", trigger: "blur" }],
    factory: [{ required: true, message: "请输入工厂!", trigger: "blur" }],
  },
});

// const searchTree = ref("searchTree");
const gutter = computed(() => {
  return disabledForm.value ? 20 : 0;
});
const span = computed(() => {
  return disabledForm.value ? 12 : 24;
});

const { queryParams, form, rules } = toRefs(data);


/** 查询字典类型列表 */
function getList() {
  loading.value = true;

  listMat(proxy.addDateRange(queryParams.value, dateRange.value)).then(
    (response) => {
      typeList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    }
  );
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

function addTreeClick(node) {
  form.value.typeName = node.name;
}

function getMatType() {
  queryMatTypeTree().then((res) => {
    // formatTree(res.data)
    matTypes.value = res.data;
  });
}
function handleSync() {
  syncLoading.value = true;
  syncErpMaterial()
    .then(() => {
      proxy.$modal.msgSuccess("同步成功");

      syncLoading.value = false;
      getList();
    })
    .catch(() => {
      syncLoading.value = false;
    });
}
// function handleTypeChange(val) {
//   for (let index = 0; index < matTypes.value.length; index++) {
//     const el = matTypes.value[index];
//     if (el.id === val.id) {
//       form.value.typeName = el.name;
//     }
//     break;
//   }
// }

function handleDetail(row) {
  disabledForm.value = true;
  reset();
  const id = row.id;
  getMat(id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "物料详情";
  });
}

/** 表单重置 */
function reset() {
  form.value = {
    name: undefined,
    type: undefined,
    typeName: undefined,
    model: undefined,
    factory: undefined,
    brand: undefined,
    measureUnit: undefined,
    packages: undefined,
    volume: undefined,
    weight: undefined,
  };
  proxy.resetForm("formRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value.typeName = undefined;
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  disabledForm.value = false;
  open.value = true;
  title.value = "添加物料";
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  selectData.value = selection;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  disabledForm.value = false;
  const equipId = row.id || ids.value;
  getMat(equipId).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "编辑物料";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateMat(form.value).then(() => {
          proxy.$modal.msgSuccess("编辑成功");
          open.value = false;
          getList();
        });
      } else {
        addMat(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const idList = row.id || ids.value.join(",");
  if (!row.id) {
    for (let index = 0; index < selectData.value.length; index++) {
      const el = selectData.value[index];
      if (el.source !== "MES") {
        proxy.$modal.msgError("仅可删除MES来源数据");
        return;
      }
    }
  }

  const codes =
    row.code ||
    ids.value
      .map((id) => typeList.value.find((item) => item.id === id)?.code)
      .join(", ");

  proxy.$modal
    .confirm('是否确认删除物料编号为"' + codes + '"的数据项？')
    .then(function () {
      return delMat({ ids: idList });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
getMatType();
getList();
</script>
